package com.huami.common.view

import android.content.Context
import android.graphics.Canvas
import android.graphics.LinearGradient
import android.graphics.Paint
import android.graphics.Shader
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatTextView
import com.weme.common.R

class GradientTextView : AppCompatTextView {
    private var startColor: Int = 0xffF13BF0.toInt()
    private var endColor: Int = 0xff8D2CFD.toInt()
    private var gradient: LinearGradient? = null

    constructor(context: Context) : super(context)
    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
        init(context, attrs)
    }

    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
        init(context, attrs)
    }

    private fun init(context: Context, attrs: AttributeSet?) {
        val typedArray = context.obtainStyledAttributes(attrs, R.styleable.GradientTextView)
        startColor = typedArray.getColor(R.styleable.GradientTextView_startColor, startColor)
        endColor = typedArray.getColor(R.styleable.GradientTextView_endColor, endColor)
        typedArray.recycle()
        invalidate()
    }


    override fun onDraw(canvas: Canvas) {
        val width = measuredWidth.toFloat()
        gradient = LinearGradient(0f, 0f, width, 0f, startColor, endColor, Shader.TileMode.CLAMP)
        val paint: Paint = paint
        paint.shader = gradient
        super.onDraw(canvas)
    }
}

